import 'package:find_friend/const/const.dart';
import 'package:find_friend/pages/mine/mine_record.dart';
import 'package:flutter/material.dart';

import 'emoji.dart';

class ConversationInputBar extends StatefulWidget {
  
  final ConversationInputBarDelegate delegate;
  _ConversationInputBarState _state;
  ConversationInputBar({Key key, this.delegate}) : super(key: key); 

  void setTextContent(String textContext) {
    this._state.setText(textContext);
  }

  void refreshUI() {
    this._state._refreshUI();
  }

  void unfocus() {
    this._state._onFocus();
  }

  @override
  _ConversationInputBarState createState() => _state = _ConversationInputBarState(delegate);
}

class _ConversationInputBarState extends State<ConversationInputBar> {

  TextEditingController _controller = TextEditingController();
  FocusNode focusNode = FocusNode();
  int selectIdx = -1;

  ConversationInputBarDelegate delegate;

  List<String> listIcons = [
    "assets/luy.png",
    "assets/tupian2.png",
    "assets/paishe.png",
    "assets/biaoqing.png",
    "assets/yuehui.png",
  ];

  void setText(String textContent) {
    if (textContent == null) {
      textContent = '';
    }
    this._controller.text =
        this._controller.text + textContent;
    this._controller.selection = TextSelection.fromPosition(
        TextPosition(offset: _controller.text.length));
    _refreshUI();
  }

  void _refreshUI() {
    setState(() {});
  }


  _ConversationInputBarState(ConversationInputBarDelegate delegate) {
    this.delegate = delegate;
  }

  @override
  void initState() {
    super.initState();

    focusNode.addListener(() { 
      if(focusNode.hasFocus){
        setState(() {
          selectIdx = -1;
        });
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _onFocus() {
    focusNode.unfocus();
    setState(() {
      selectIdx = -1;
    });
  }


  @override
  Widget build(BuildContext context) {
    final bottom = MediaQuery.of(context).padding.bottom;
    final size = MediaQuery.of(context).size;
    final width = (size.width - 16.5 * 2) / listIcons.length;
    return Container(
      color: Color(0xe6ffffff),
      padding: EdgeInsets.only(bottom: bottom),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Row(
            children: [
              Expanded(
                child: Container(
                  margin: const EdgeInsets.all(10),
                  height: 40,
                  child: TextField(
                    onSubmitted: _clickSendMessage,
                    controller: _controller,
                    maxLines: 10,
                    decoration:InputDecoration(
                          hintText: "说点什么吧～",
                          counterText: "",
                          focusedBorder: OutlineInputBorder(
                          borderRadius: const BorderRadius.all(Radius.circular(25)),
                          borderSide: const BorderSide(width: 1.5, color: Colors.black),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: const BorderRadius.all(Radius.circular(25)),
                          borderSide: const BorderSide(width: 1.5, color: Colors.black),
                        ),
                        border: OutlineInputBorder(
                          borderRadius: const BorderRadius.all(Radius.circular(25)),
                          borderSide: const BorderSide(width: 1.5, color: Colors.black),
                        ),
                        contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
                    ),
                    focusNode: focusNode,
                    autofocus: false,
                  ),
                ),
              ),
              GestureDetector(
                onTap: () => _clickSendMessage(_controller.text),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  margin: const EdgeInsets.only(right: 10),
                  decoration: BoxDecoration(
                    color: APP_main_color,
                    borderRadius: BorderRadius.circular(20)
                  ),
                  child: Text("发送", style: instanceTextStyle(14, Colors.white)),
                ),
              )
            ],
          ),
          Padding(
            padding: const EdgeInsets.only(bottom:10.0, left: 16.5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: listIcons.map((e){
                return GestureDetector(
                  onTap: (){
                    focusNode.unfocus();
                    final temp = listIcons.indexOf(e);
                    setState(() {
                      // 相册选择, 相机, 场景, 不需要选中的状态
                      if(temp == selectIdx || temp == 4 || temp == 2 || temp == 1) {
                        selectIdx = -1;
                      } else {
                        selectIdx = temp;
                      }
                    });
                    
                    // 相机选择, 相册选择
                    if(temp == 2 || temp == 1) {
                      _clickSendImage(temp);
                    }

                    // 约会场景
                    if(temp == 4) {
                      if(delegate != null) {
                        delegate.willGotoScene();
                      }
                    }
                  },
                  child: Container(
                    width: width,
                    height: 25,
                    child: Image.asset(e, color: listIcons.indexOf(e) == selectIdx ? APP_main_color : null,),
                  ),
                );
              }).toList(),
            ),
          ),
          Offstage(
            offstage: selectIdx != 0,
            child: Container(
              padding: const EdgeInsets.only(bottom: 40),
              child: XMineRecordVoiceWidget(
                mintime: 1,
                noticelabel: "长按录音",
                onRecordFinish: _clickSendVoice,
              ),
            ),
          ),
          Offstage(
            offstage: selectIdx != 3,
            child: EmojiWidget(
              onTapDelete: (){
                String temp = _controller.text;
                if(temp.length == 0) return;
                String val = String.fromCharCode(temp.runes.last);
                _controller.text = temp.substring(0, temp.length - val.length);
              },
              onTapEmoji: (emoji){
                String temp = _controller.text;
                _controller.text = temp + emoji;
              },
              onTapFace: (faceurl){
                if(this.delegate != null) {
                  this.delegate.willSendFaceEmoji(faceurl);
                }
              },
            ),
          ),
         
        ],
      ),
    );
  }

  void _clickSendMessage(String messageStr) {
    if (messageStr == null || messageStr.length <= 0) {
      return;
    }

    if (this.delegate != null) {
      this.delegate.willSendText(messageStr);
    } else {
      print("没有实现 BottomInputBarDelegate");
    }
    _controller.text = '';
  }

  void _clickSendVoice(String path, int duration) {
    if (this.delegate != null && path.length > 0) {
      this.delegate.willSendVoice(path, duration);
    } else {
      print("没有实现 BottomInputBarDelegate || 录音路径为空");
    }
  }

  void _clickSendImage(int idx) {
    if (this.delegate != null) {
      if(idx == 1){
        this.delegate.willSendAlbum();
      } else {
        this.delegate.willSendPhoto();
      }
    } else {
      print("没有实现 BottomInputBarDelegate");
    }
  }
}

abstract class ConversationInputBarDelegate {

  ///即将发送消息
  void willSendText(String text);

  ///即将发送语音
  void willSendVoice(String path, int duration);

  ///即将开始录音
  void willStartRecordVoice();

  ///即将停止录音
  void willStopRecordVoice();

  ///点击了加号按钮
  void didTapExtentionButton();

  ///发送图 
  void willSendAlbum();
  // 发送表情包
  void willSendFaceEmoji(String url);
  // 拍照
  void willSendPhoto();

  // 去到场景
  void willGotoScene();

  ///输入框内容变化监听
  void onTextChange(String text);
}

